package com.lagou.rpc.consumer.client;

import com.lagou.rpc.consumer.handler.RpcClientHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

/**
 *   客户端 需要完成的功能
 *   1. 连接netty服务端
 *   2. 提供给 调用者  主动关闭资源的方法
 *   3. 提供消息发送的方法
 */
public class RpcClient {

    private  EventLoopGroup group;
    private Channel channel;
    private String ip;
    private int port;
    private RpcClientHandler rpcClientHandler = new RpcClientHandler();
    //RpcClientHandler 是一个线程 因为实现了callable  创建一个线程池
    private ExecutorService executorService = Executors.newCachedThreadPool();

    // 在new  RpcClient的时候，把ip和port传递进来
    public RpcClient(String ip, int port) {
        this.ip = ip;
        this.port = port;
        initClient();
    }

    /**
     *   1. 连接netty服务端
     */
    public void initClient(){
        try {
            // 1. 创建线程组
            group = new NioEventLoopGroup();
            // 2. 创建客户端启动助手
            Bootstrap bootstrap = new Bootstrap();
            // 3. 设置参数
            bootstrap.group(group)
                    .channel(NioSocketChannel.class)
                    .option(ChannelOption.SO_KEEPALIVE,Boolean.TRUE)  // 设置活跃状态
                    .option(ChannelOption.CONNECT_TIMEOUT_MILLIS,3000)  // 设置超时时间
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            ChannelPipeline pipeline = socketChannel.pipeline();
                            pipeline.addLast(new StringDecoder());
                            pipeline.addLast(new StringEncoder());
                            // 添加客户端处理类
                            pipeline.addLast(rpcClientHandler);
                        }
                    });
            // 4. 连接netty服务端
            channel = bootstrap.connect(ip, port).sync().channel();
        } catch (InterruptedException e) {
            e.printStackTrace();
            if (channel != null){
                channel.close();
            }
            if (group != null){
                group.shutdownGracefully();
            }
        }
    }

    /**
     * 提供给 调用者  主动关闭资源的方法
     */
    public void close(){
        if (channel != null){
            channel.close();
        }
        if (group != null){
            group.shutdownGracefully();
        }
    }

    /**
     * 提供消息发送的方法
     * @return 返回值是  服务端发送过来的消息
     */
    public Object send(String msg) throws ExecutionException, InterruptedException {// 参数就是向服务端发送的消息，也就是转换成json字符串的rpcRequest
        rpcClientHandler.setRequestMessage(msg);// set方法
        Future submit = executorService.submit(rpcClientHandler);
        Object o = submit.get();//submit.get()获取的就是服务端发送来的消息，对应RpcClientHandler中的call方法
        return o;
    }


}
